import 'dart:convert';
import 'dart:io';
import 'dart:ui';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mahjong/entity/Restful.dart';
import 'package:mahjong/entity/UserEntityInfo.dart';
import 'package:mahjong/page/GameIndex.dart';
import 'package:mahjong/util/CacheUtil.dart';
import 'package:mahjong/util/CustomRoute.dart';
import 'package:mahjong/util/CustomerDialog.dart';
import 'package:mahjong/util/DictionaryConst.dart';
import 'package:mahjong/util/EncryptHelper.dart';
import 'package:mahjong/util/Http.dart';
import 'package:mahjong/widget/BubbleWidget.dart';
import 'package:mahjong/widget/ITextFiled.dart';
import 'package:mahjong/const/CacheConst.dart';
import 'package:mahjong/util/RegExpConstant.dart';
import 'package:mahjong/page/common/UserAgreement.dart';
import 'package:provider/provider.dart';
import 'package:mahjong/page/common/RegisterAccount.dart';

class UserLoginWidget extends StatefulWidget {
  @override
  _UserLoginWidgetState createState() => _UserLoginWidgetState();
}

class _UserLoginWidgetState extends State<UserLoginWidget> {
  GlobalKey<ScaffoldState> globalKey = GlobalKey<ScaffoldState>();

  TextFiledValidata _userNameVlidata;
  TextFiledValidata _pwdVlidata;
  //第一部分 第一层 渐变背景
  Container buildBackground() {
    return Container(
      width: double.infinity,
      height: double.infinity,
      decoration: BoxDecoration(
        //线性渐变
        gradient: LinearGradient(
          //渐变角度
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          //渐变颜色组
          colors: [
            Colors.lightBlue.withOpacity(0.3),
            Colors.lightBlueAccent.withOpacity(0.3),
            Colors.blue.withOpacity(0.3),
          ],
        ),
      ),
    );
  }

//第三部分 高斯模糊
  Widget buildBlureWidget() {
    return BackdropFilter(
      filter: ImageFilter.blur(sigmaX: 0.3, sigmaY: 0.3),
      child: Container(
        color: Colors.grey.withOpacity(0.2),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _userNameVlidata = TextFiledValidata.init(
        show: false, tips: "账号不合法", paretten: RegExpConstant.userName);
    _pwdVlidata = TextFiledValidata.init(
        show: false, tips: "请输入密码", paretten: "^.{5,10}");
    WidgetsBinding.instance.addPostFrameCallback((context) {
      Future.delayed(Duration(milliseconds: 500), () {
        showDialog<Null>(
            context: this.context,
            barrierDismissible: false,
            builder: (BuildContext context) {
              return UserAgreement();
            });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: Container(
      child: Stack(
        children: [
          // 背景
          Positioned(
              child: Container(
            width: double.infinity,
            height: double.infinity,
            child: Image.asset(
              "images/mahjong/background/login_bg.png",
              fit: BoxFit.cover,
            ),
          )),
          Align(
              alignment: Alignment(-0.8, -0.8),
              child: Container(
                alignment: Alignment.center,
                height: ScreenUtil().screenWidth / 4 / 4.5,
                width: ScreenUtil().screenWidth / 4,
                child: Image.asset(
                  "images/logo/logo.png",
                  fit: BoxFit.cover,
                ),
              )),
          BubbleWidget(
            bubbleCout: 3,
          ),
          buildBlureWidget(),
          Positioned(
            bottom: MediaQuery.of(context).size.height / 8,
            left: MediaQuery.of(context).size.width / 3,
            right: MediaQuery.of(context).size.width / 3,
            child: Column(
              children: [
                ITextFiled(
                  400.w,
                  60.h,
                  hintText: "请输入账号",
                  defaultStr: "",
                  preIcon: Icons.email,
                  textFiledValidata: _userNameVlidata,
                ),
                SizedBox(
                  height: MediaQuery.of(context).size.height / 8 / 2,
                ),
                ITextFiled(
                  400.w,
                  60.h,
                  hintText: "密码",
                  defaultStr: "",
                  obscureText: true,
                  preIcon: Icons.fingerprint,
                  textFiledValidata: _pwdVlidata,
                ),
                SizedBox(
                  height: MediaQuery.of(context).size.height / 8 / 2,
                ),
                Container(
                  child: Column(
                    children: [
                      Container(
                          color: Colors.blue.withOpacity(0.8),
                          width: MediaQuery.of(context).size.width / 3,
                          height: MediaQuery.of(context).size.height / 10,
                          child: OutlinedButton(
                            child: Text(
                              "登录",
                              style: TextStyle(
                                  color: Colors.white, fontSize: 20.sp),
                            ),
                            onPressed: () {
                              if (_userNameVlidata.check() &&
                                  _pwdVlidata.check()) {
                                CustomerDialog.showVerification(context,
                                    (data) async {
                                  String decodePwd = await EncryptHelper.encode(
                                      _pwdVlidata.value);
                                  UserEntityInfo userInfo = UserEntityInfo(
                                      verificationMode: data,
                                      sysUser: SysUser.init(
                                          _userNameVlidata.value, decodePwd));
                                  Http.getInstance().request<Restful>(
                                      DictionaryConst.login,
                                      type: RequestEnum.POST,
                                      contentType: ContentType.json,
                                      showLoading: true,
                                      loadingMsg: "登录中...",
                                      data: userInfo.toString(),
                                      success: (data) {
                                    var loginUser = Provider.of<UserEntityInfo>(
                                        context,
                                        listen: false);
                                    loginUser.updateInfo(
                                        UserEntityInfo.fromJson(data.body));

                                    CacheUtil.preferencesInstance.setString(
                                        CacheConst.userInfo,
                                        json.encode(data.body));

                                    Navigator.of(context).pushAndRemoveUntil(
                                        new CustomRoute(
                                            GameIndex(), AnimationEnum.zoom),
                                        (route) => route == null);
                                  }, error: (data) {
                                    BotToast.showText(text: data.msg);
                                  });
                                });
                              } else {
                                setState(() {});
                              }
                            },
                          )),
                    ],
                  ),
                )
              ],
            ),
          ),
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: Container(
              alignment: Alignment.center,
              color: Colors.black.withOpacity(0.2),
              height: MediaQuery.of(context).size.height / 12,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Text(
                    "App V1.1 Res V1.1.1.1",
                    style: TextStyle(color: Colors.white, fontSize: 20.sp),
                  ),
                  Text("抵制不良游戏,拒绝盗版游戏,注意自我保护,谨防上当受骗;",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 15.sp,
                      )),
                ],
              ),
            ),
          ),
          Align(
            alignment: Alignment(0, 0.95),
            child: Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    "找回密码",
                    style: TextStyle(color: Colors.white, fontSize: 18.sp),
                  ),
                  SizedBox(
                    height: 40.h,
                    child: Container(
                      margin: EdgeInsets.symmetric(
                          horizontal: 10.w, vertical: 10.h),
                      child: DecoratedBox(
                        decoration: BoxDecoration(color: Colors.white),
                      ),
                      height: 40.h,
                      width: 1,
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text(
                        "登录即同意",
                        style: TextStyle(fontSize: 18.sp, color: Colors.white),
                      ),
                      InkWell(
                        child: Text(
                          "<<逍遥棋牌>>",
                          style: TextStyle(
                              decoration: TextDecoration.underline,
                              fontSize: 18.sp,
                              color: Colors.yellow),
                        ),
                        onTap: () {
                          showDialog<Null>(
                              context: context,
                              barrierDismissible: false,
                              builder: (BuildContext context) {
                                return UserAgreement();
                              });
                        },
                      ),
                      Text(
                        "用户协议",
                        style: TextStyle(fontSize: 18.sp, color: Colors.white),
                      )
                    ],
                  ),
                  SizedBox(
                    height: 40.h,
                    child: Container(
                      margin: EdgeInsets.symmetric(
                          horizontal: 10.w, vertical: 10.h),
                      child: DecoratedBox(
                        decoration: BoxDecoration(color: Colors.white),
                      ),
                      height: 40.h,
                      width: 1,
                    ),
                  ),
                  InkWell(
                    child: Text("注册新用户",
                        style: TextStyle(color: Colors.white, fontSize: 18.sp)),
                    onTap: () {
                      showDialog<Null>(
                          context: context,
                          barrierDismissible: false,
                          builder: (BuildContext context) {
                            return RegisterAccount();
                          });
                    },
                  )
                ],
              ),
            ),
          )
        ],
      ),
    ));
  }
}
